package com.linfeng.api.service.impl;

import com.linfeng.api.redis.util.RedisUtils;
import com.linfeng.api.service.SearchService;
import com.linfeng.api.util.hdk.HdkApiRequest;
import com.linfeng.api.util.hdk.HdkConfig;
import com.linfeng.api.util.hdk.request.ApiKeyword;
import com.linfeng.api.util.hdk.request.ApiSearchGoods;
import com.linfeng.common.constant.RedisKeyConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author linfeng
 * @date 2021/1/20 13:29
 */
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private HdkConfig hdkConfig;

    @Override
    public String keyword() {
        String redisKey = RedisKeyConstant.API_DATA + "keyword";
        String data = (String) redisUtils.get(redisKey);
        if (data == null || data.equals("")) {
            ApiKeyword apiKeyword = new ApiKeyword();
            apiKeyword.setApikey(hdkConfig.getAppkey());
            try {
                String response = HdkApiRequest.doRequest(apiKeyword);
                redisUtils.set(redisKey,response,1,TimeUnit.HOURS);
                return response;
            } catch (Exception e) {
                e.printStackTrace();
                return e.getMessage();
            }
        }
        return data;
    }

    @Override
    public String goods(String keyword, Integer tag, Integer page) {
        String redisKey = RedisKeyConstant.API_DATA + "goods:" + keyword + "-" + tag + "-" + page;
        String data = (String) redisUtils.get(redisKey);
        if (data == null || data.equals("")) {
            ApiSearchGoods apiSearchGoods = new ApiSearchGoods();
            apiSearchGoods.setApikey(hdkConfig.getAppkey());
            apiSearchGoods.setSort(tag);
            apiSearchGoods.setMin_id(page);
            apiSearchGoods.setKeyword(keyword);
            try {
                String response = HdkApiRequest.doRequest(apiSearchGoods);
                redisUtils.set(redisKey,response,1,TimeUnit.HOURS);
                return response;
            } catch (Exception e) {
                e.printStackTrace();
                return e.getMessage();
            }
        }
        return data;
    }
}
